package com.jack.helloworld.util;

import android.os.Environment;
import android.os.StatFs;

import com.orhanobut.logger.Logger;

import java.io.File;

/**
 * 文件管理工具类
 */
public class FileUtil {

	// 手机sd卡可用的存储空间
	public static String availableSdcardSize() {
		double size = 0.0;
		String sizeString = "0.00";
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			/** 获取存储卡路径 */
			File sdcardDir = Environment.getExternalStorageDirectory();
			size = used(sdcardDir.getPath());
			sizeString = convert(size);
		} else {
            Logger.d("SD卡未安装,无法获取SD卡可用ROM内存");
        }
		return sizeString;
	}

	// 手机可用的ROM存储空间
	public static String availableRomSize() {
		String DirPath = "/data/data";
		double size = 0.00;
		String sizeString = "0.00";
		try {
			size = used(DirPath);
			sizeString = convert(size);
		} catch (Exception e) {
            Logger.e(e, "手机内存未加载，无法获取MOM可用空间大小");
		}
		return sizeString;
	}

	public static double used(String DirPath) {
		/** StatFs 看文件系统空间使用情况 */
		StatFs statFs = new StatFs(DirPath);
		/** Block 的 size */
		long blockSize = (long) statFs.getBlockSize();
		/** 可用的 Block 数量 */
		double availableBlocks = (double) statFs.getAvailableBlocks();
		// 可用空间大小,MIB
		double size = (blockSize * availableBlocks) / 1024 / 1024;
		return size;
	}

	// double类型保留2位有效数字
	public static String convert(double d) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");
		return df.format(d);
	}
}
